<template>
<el-container class="summary-wrap">
  <el-aside class="summary-left" v-if="treeCodeType || mTreeCodeType" width="200px">
        <el-input v-if="treeFilterFieldKey && treeFilterType=='1'?
            true : mTreeFilterFieldKey && mTreeFilterType=='1'? true : false" 
            placeholder="输入关键字" suffix-icon="el-icon-search" 
            v-model="treeFilterText" :clearable="true" size="small"></el-input>
        <!--代码转参1 SQL，2静态-->
        
        <template v-if="treeCodeType">
            <dx-treelist ref="treelist" v-if="treeFilterType=='1'" :code-type="treeCodeType" @node-click="nodeClick" :condition="treefilterCondiValue(treeFilterText)"></dx-treelist>
            <dx-treelist ref="treelist" v-else-if="treeFilterType=='2'" :code-type="treeCodeType" @node-click="nodeClick" :filterable="true"></dx-treelist>
            <dx-treelist ref="treelist" v-else :code-type="treeCodeType" @node-click="nodeClick"></dx-treelist>
        </template>
        <template v-if="mTreeCodeType">
            <dx-treelist ref="treelist" v-if="mTreeFilterType=='1'" :code-type="mTreeCodeType" @node-click="nodeClick" :condition="treefilterCondiValue(treeFilterText)"></dx-treelist>
            <dx-treelist ref="treelist" v-else-if="mTreeFilterType=='2'" :code-type="mTreeCodeType" @node-click="nodeClick" :filterable="true"></dx-treelist>
            <dx-treelist ref="treelist" v-else :code-type="mTreeCodeType" @node-click="nodeClick"></dx-treelist>
        </template>
  </el-aside>
  <el-main :class="!(treeCodeType || mTreeCodeType)?'summary-main':'summary-main-tree'">
      <el-row>

            <el-form ref="searchForm" class="searchForm" :model="searchForm" :inline="true">
                <!--过滤字段-->
                <template v-for="(item,index) in filterFields">
                    <!--区间构造-->
                    <template v-if="item.express>20">
                        <el-form-item v-if="!(item.visible&&item.visible=='2')" :prop="item.columnName" :label="item.columnLabel" :key="index+'_start'">
                            <dx-ctrl :type="item.ctrlName" v-model="searchForm[item.columnName+'_start']" :code-type="item.codeType" :clearable="true"></dx-ctrl>
                        </el-form-item>
                        <el-form-item v-if="!(item.visible&&item.visible=='2')" :prop="item.columnName" label="~" :key="index+'_end'">
                            <dx-ctrl :type="item.ctrlName" v-model="searchForm[item.columnName+'_end']" :code-type="item.codeType" :clearable="true"></dx-ctrl>
                        </el-form-item>
                    </template>
                     <!--一般构造-->
                    <template v-else>
                        <el-form-item v-if="!(item.visible&&item.visible=='2')" :prop="item.columnName" :label="item.columnLabel" :key="index">
                            <dx-ctrl :type="item.ctrlName" :condition="cascadeCondiValue(form,item)" v-model="searchForm[item.columnName]" :code-type="item.codeType" :clearable="true"></dx-ctrl>
                        </el-form-item>
                    </template>
                </template>
                <el-form-item v-if="filterFields && filterFields.length>0">
                    <el-button type="primary" @click="search" v-if="showBtnFunc('Query',currentRow) && (buttons.length==0 ||in_array('Query',buttons))">{{mLabel['searchLabel']}}</el-button>
                </el-form-item>
                <el-form-item  v-if="showBtnFunc('Add',currentRow) && (buttons.length==0 || in_array('Add',buttons))">
                    <el-button type="primary" @click="add">{{mLabel['addLabel']}}</el-button>
                </el-form-item>
                <el-form-item v-if="showBtnFunc('Export',currentRow) && (buttons.length==0 || in_array('ExportExcel',buttons))">
                    <el-button type="primary" @click="exportExcel">{{mLabel['exportLabel']}}</el-button>
                </el-form-item>
                <slot name="buttonSlot" :data="{currentRow:currentRow ,queryData:searchForm}"></slot>
            </el-form>
            <!--表格，根据是否有tab页来构造-->
            <template v-if="tabs && tabs.length>0">
            <el-tabs type="border-card" v-model="tabName" @tab-click="tabClick">
                <el-tab-pane name="list">
                    <span slot="label"><i class="fa fa-list"></i> {{mLabel['listLabel']}}</span>
                    <el-table :data="tableData" v-if="summaryFields && summaryFields.length>0" style="width:100%" 
                        @current-change="handleCurrentChange" 
                        @selection-change="handleSelectionChange"
                        @sort-change="sortChange">
                        <el-table-column v-if="checkboxSelect" fixed type="selection" width="40" align="center"></el-table-column>
                        <el-table-column v-if="lineNumber" fixed type="index" label="序号" align="center" width="50"></el-table-column>
                        <template v-for="(col ,index) in summaryFields">
                            <dx-table-column :prop="col.columnName" v-if="col.codeType"
                            :fixed="col.fixed"
                            :align="col.align"
                            :label="col.columnLabel"
                            :width="col.width"
                            :formatter="formatter"
                            :sortable="col.sortable"
                            :show-overflow-tooltip="true"
                            :code-type="col.codeType"
                            :ctrlName="col.ctrlName"
                            :key="index"></dx-table-column>
                            <el-table-column :prop="col.columnName" v-else
                            :fixed="col.fixed"
                            :align="col.align"
                            :label="col.columnLabel"
                            :width="col.width"
                            :sortable="col.sortable"
                            :formatter="formatter"
                            :show-overflow-tooltip="true"
                            :key="index"></el-table-column>
                        </template>
                        <slot name="operationSlot" v-if="$scopedSlots['operationSlot']?$scopedSlots['operationSlot']:$slots['operationSlot']" :row="scope.row"></slot>
                        <el-table-column v-else-if="buttons.length==0 || in_array('Edit',buttons) ||
                                                    in_array('View',buttons) || 
                                                    in_array('Delete',buttons) || ($scopedSlots['appendOperationSlot']?$scopedSlots['appendOperationSlot']:$slots['appendOperationSlot'])"
                                                    fixed="right" align="center" header-align="center" :label="mLabel['operationLabel']" :width="opWidth">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" v-if="showBtnFunc('Edit',scope.row) && (buttons.length==0 || in_array('Edit',buttons))" @click="edit(scope.row)">{{scope.row['_edit_label'] || mLabel['editLabel']}}</el-button>
                                <el-button type="text" size="small" v-if="showBtnFunc('View',scope.row) && (buttons.length==0 || in_array('View',buttons))" @click="view(scope.row)">{{scope.row['_view_label'] || mLabel['viewLabel']}}</el-button>
                                <el-button type="text" size="small" v-if="showBtnFunc('Delete',scope.row) && (buttons.length==0 || in_array('Delete',buttons))" @click="del(scope.row)">{{scope.row['_delete_label'] || mLabel['deleteLabel']}}</el-button>
                                <slot name="appendOperationSlot" :row="scope.row"></slot>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="block">
                        <el-pagination
                        @current-change="handleCurrentPageChange"
                        :current-page="page"
                        :page-size="pageSize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                        </el-pagination>
                    </div>
                </el-tab-pane>
                <el-tab-pane v-for="(tab,index) in tabs" :key="index+1" :name="tab.name">
                    <span slot="label"><i v-if="tab.icon" :class="tab.icon"></i> {{tab.label}}</span>
                    <slot v-if="tab.name" :name="tab.name"></slot>
                </el-tab-pane>
            </el-tabs>
            </template>
            <template v-else>
                <el-table :data="tableData" v-if="summaryFields && summaryFields.length>0" style="width:100%" 
                    @current-change="handleCurrentChange" 
                    @selection-change="handleSelectionChange"
                    @sort-change="sortChange">
                    <el-table-column v-if="checkboxSelect" fixed type="selection" width="40" align="center"></el-table-column>
                    <el-table-column v-if="lineNumber" fixed type="index" label="序号" align="center" width="50"></el-table-column>
                    <template v-for="(col ,index) in summaryFields">
                        <dx-table-column :prop="col.columnName" v-if="col.codeType"
                        :fixed="col.fixed"
                        :align="col.align"
                        :label="col.columnLabel"
                        :width="col.width"
                        :formatter="formatter"
                        :sortable="col.sortable"
                        :show-overflow-tooltip="true"
                        :code-type="col.codeType"
                        :ctrl-name="col.ctrlName"
                        :key="index"></dx-table-column>
                        <el-table-column :prop="col.columnName" v-else
                        :fixed="col.fixed"
                        :align="col.align"
                        :label="col.columnLabel"
                        :width="col.width"
                        :sortable="col.sortable"
                        :formatter="formatter"
                        :show-overflow-tooltip="true"
                        :key="index"></el-table-column>
                    </template>
                    <slot name="operationSlot" v-if="$scopedSlots['operationSlot']?$scopedSlots['operationSlot']:$slots['operationSlot']" :row="scope.row"></slot>
                    <el-table-column v-else-if="buttons.length==0 || in_array('Edit',buttons) ||
                                                in_array('View',buttons) || 
                                                in_array('Delete',buttons) || ($scopedSlots['appendOperationSlot']?$scopedSlots['appendOperationSlot']:$slots['appendOperationSlot'])" fixed="right" align="center" header-align="center" :label="mLabel['operationLabel']" :width="opWidth">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" v-if="showBtnFunc('Edit',scope.row) && (buttons.length==0 || in_array('Edit',buttons))" @click="edit(scope.row)">{{scope.row['_edit_label'] || mLabel['editLabel']}}</el-button>
                            <el-button type="text" size="small" v-if="showBtnFunc('View',scope.row) && (buttons.length==0 || in_array('View',buttons))" @click="view(scope.row)">{{scope.row['_view_label'] || mLabel['viewLabel']}}</el-button>
                            <el-button type="text" size="small" v-if="showBtnFunc('Delete',scope.row) && (buttons.length==0 || in_array('Delete',buttons))" @click="del(scope.row)">{{scope.row['_delete_label'] || mLabel['deleteLabel']}}</el-button>
                            <slot name="appendOperationSlot" :row="scope.row"></slot>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="block">
                    <el-pagination
                    @current-change="handleCurrentPageChange"
                    :current-page="page"
                    :page-size="pageSize"
                    layout="total, prev, pager, next, jumper"
                    :total="total">
                    </el-pagination>
                </div>
            </template>
            <el-dialog :visible.sync="dialogVisible" :width="dialogWidth" :fullscreen="dialogFullscreen" :modal-append-to-body="false">
                <span slot="title">
                    <!-- <span v-if="opFlag=='Add'">{{mLabel['addLabel']}}</span>
                    <span v-if="opFlag=='Edit'">{{mLabel['editLabel']}}</span>
                    <span v-if="opFlag=='View'">{{mLabel['viewLabel']}}</span> -->
                    <span>{{dialogTitle}}</span>
                </span>
                <dx-input v-if="dialogVisible && in_array(opFlag,['Add','Edit'])" :unit-name="unitName" 
                    :cascadeMethod="cascadeMethod" 
                    :dialogVisible.sync="dialogVisible" 
                    :defaultValue="defaultValue" 
                    :id="currentId"
                    :saveText="saveText"
                    :updateText="updateText"
                    :cancelText="cancelText"
                    @dataChange="notifyDataChange">
                    <template v-for="(value, key) in $scopedSlots" :slot="key" slot-scope="scope">
                        <slot v-if="key.indexOf('add_slot') || key.indexOf('edit_slot')" :name="key" :data="scope.data"></slot>
                    </template>
                </dx-input>
                <dx-view v-if="dialogVisible && opFlag=='View'" :unit-name="unitName" :dialogVisible.sync="dialogVisible" :id="currentId"
                :cancelText="cancelText">
                    <template v-for="(value, key) in $scopedSlots" :slot="key" slot-scope="scope">
                        <slot v-if="key.indexOf('view_slot')" :name="key" :data="scope.data"></slot>
                    </template>
                </dx-view> 
            </el-dialog>
        </el-row>


  </el-main>
</el-container>
 
    
</template>
<script>
import DxCtrl from '../../ui/dx-ctrl'
import DxTreelist from '../../ui/dx-treelist'
import DxInput from '../../ui/unit/dx-input'
import DxView from '../../ui/unit/dx-view'
import DxTableColumn from '../../ui/dx-table-column'
import http from '../../../../assets/js/http.js'
import {unitProvider} from '../../../../assets/js/provider.js'
import toolkit from '../../../../assets/js/toolkit.js'
export default {

    components : {
        DxCtrl,
        DxTableColumn,
        DxInput,
        DxView,
        DxTreelist
    },
    props :{
        unitName : String,
        dialogWidth : {type:String,default:'60%'},
        dialogFullscreen : {type:Boolean,default:false},
        operationWidth : Number,

        defaultQueryValue : {type:Object,default:()=>{}},
        condition : {type:Object,default:()=>{}},
        treeCodeType : String,
        treeFieldKey : String,
        treeNodeMethod : {type : Function ,default: null},
        addMethod : {type : Function,default : null},
        editMethod : {type : Function,default : null},
        showButtonMethod : {type : Function,default : ()=>{return true}},
        viewMethod : {type : Function,default : null},
        searchMethod : {type : Function,default : null},
        deleteMethod : {type : Function,default : null},
        initMethod : {type : Function,default : null},
        label : {type : Object,default : ()=>{}}, //{addLabel:'新增',editLabel:'修改',deleteLabel:'删除',viewLabel:'查看',searchLabel:'查询',exportLabel:'导出',operationLabel:'操作',listLabel:'列表'}
        treeFilterFieldKey : String,
        treeFilterType : {type : String ,default : '1'},//1 sql筛选,2 静态
        autoSubmit : {
            type : Boolean,
            default : true
        },
        tabs : Array,//[{label:'地图模式',name:'map'},{label:'地图模式1',name:'map1'}]
        cascadeMethod : {type:Function,default:()=>true},//级联
        saveText : String,
        updateText : String,
        cancelText : String
    },
    data(){
        return {
            dialogVisible : false,
            dialogTitle : '',
            opFlag : 'Add',
            tabName : 'list',
            checkboxSelect : false,
            lineNumber : false,
            searchForm : {
                sortProperty : '',
                sortDescOrAsc : '',
            },
            keys : [],
            summaryFields : [],
            filterFields : [],
            formatters : {},
            tableData : [],
            page : 1,
            pageSize : 10,
            total : 5,
            opWidth : this.operationWidth ? this.operationWidth : 130,
            buttons : [],
            currentRow : {},
            currentId : '',
            defaultValue : {},

            treeFilterText : '',//过滤文本
            //树
            mTreeCodeType : '',
            mTreeFieldKey : '',
            mTreeFilterFieldKey : '',
            mTreeFilterType:'',
            currentNode : null,
        }
    },
    watch : {
        defaultQueryValue(val,oldVal){
            if(!this.eq_object(val,oldVal)){
                this.initDefaultQueryValue();
            }
        }
    },
    computed : {

        showBtnFunc(){
            return (type,row)=>{
                return this.showButtonMethod(type,row);
            }
        },
        mLabel(){
            let defaultLabel = {
                addLabel : '新增',
                editLabel : '修改',
                deleteLabel : '删除',
                viewLabel : '查看',
                searchLabel : '查询',
                exportLabel : '导出',
                operationLabel : '操作',
                listLabel:'列表'
            };
            if(this.label){
                return Object.assign(defaultLabel,this.label);
            }
            return defaultLabel;
        },
        treefilterCondiValue(){
            return (text) =>{
                let condition = null;
                
                if((this.treeFilterFieldKey||this.mTreeFilterFieldKey) && text){
                    condition = {};
                    condition[this.treeFilterFieldKey||this.mTreeFilterFieldKey] = text;
                }
                
                return condition;
            }
        },
        cascadeCondiValue(){
            return (obj,f)=>{
                let condition = {};
                if(f.cascadeField){
                    condition[f.cascadeField] = obj[f.cascadeField] || '';
                }
                return condition;
            }
        }
    },

    methods : {
        tabClick(){
           this.$emit("tab-click",{name : this.tabName , queryData : this.searchForm});
        },
        
        nodeClick(node){

            let flag = true;

            this.currentNode = node;
            if(this.treeNodeMethod){
                flag = this.treeNodeMethod(node, this.searchForm, this.defaultValue);
            }
            
            if(flag){

                if(this.treeFieldKey || this.mTreeFieldKey){
                    this.searchForm[this.treeFieldKey || this.mTreeFieldKey] = node.id;
                }
                this.$nextTick(()=>{ 
                    this.getDataOfPager();
                });
            }
        },
        formatter(row, column){
            let formatter = this.formatters[column.property];
            if(formatter && row[column.property]){
                formatter = "this." + formatter;
                if (typeof (eval(formatter)) != "function") {
                    console.error('函数不存在!');
                    return "";
                }
                return eval(formatter + "(row, column);");
            }else{
                return row[column.property];
            }

        },
        getKeyValue(){
            let values = [];
            if(this.currentRow){
                // return {...keys} = currentRow;
                // console.log(this.keys);
                this.keys.forEach(key => {
                    if(this.currentRow[key]){
                        values.push(this.currentRow[key]) 
                    }
                });
            }
            return values;
        },
        //树加载时看下有没有默认值
        // treeLoaded(){
        //     let mTreelist = this.$refs.treelist;
        //     if(!this.currentNode || !mTreelist){
        //         return;
        //     }
        //     this.$nextTick(()=>{
        //         mTreelist.setCurrentKey(this.currentNode.id);
        //     });
        // },
        //数据更改
        notifyDataChange(){
            this.getDataOfPager();

            let mTreelist = this.$refs.treelist;
            if(mTreelist){
                let defaultExpandKeys = null,currentId = null;
                if(this.currentNode){
                    currentId = this.currentNode.id;
                    defaultExpandKeys = [currentId]
                }
                if(Array.isArray(mTreelist)){
                    mTreelist.forEach(item=>{
                        item.refresh(defaultExpandKeys,currentId);
                    });
                }else{
                    mTreelist.refresh(defaultExpandKeys,currentId);
                }
                
            }
            
        },
        search(){
            this.page = 1;
            this.$emit('search' , this.searchForm);
            this.getDataOfPager();
        },
        exportExcel(){
            this.$emit('export-excel' , this.searchForm);
            this.download("unit/ins/exportExcel?unitName="+this.unitName,this.search);
        },
        add(){
            if(this.addMethod){
                if(!this.addMethod.call(this ,this.searchForm)){
                    return;
                }
            }
            this.currentId = '';
            this.dialogVisible = true;
            this.dialogTitle = this.mLabel.addLabel;
            this.opFlag = 'Add';
            if(this.treeFieldKey || this.mTreeFieldKey){
                this.defaultValue[this.treeFieldKey || this.mTreeFieldKey] = this.searchForm[this.treeFieldKey || this.mTreeFieldKey];

               
            }
            let keyValue = this.getKeyValue();
        },
        view(row){
            this.currentRow  = row;
            if(this.viewMethod){
                if(!this.viewMethod.call(this , row ,this.searchForm)){
                    return;
                }
            }
            this.dialogVisible = true;
            this.dialogTitle = row['_view_label'] || this.mLabel.viewLabel;
            this.opFlag = 'View';

            let keyValue = this.getKeyValue();
            this.currentId = keyValue;
        },
        edit(row){
            this.currentRow  = row;
            if(this.editMethod){
                if(!this.editMethod.call(this , row ,this.searchForm)){
                    return;
                }
            }
            this.dialogVisible = true;
            this.dialogTitle = row['_edit_label'] || this.mLabel.editLabel;
            this.opFlag = 'Edit';
      
            let keyValue = this.getKeyValue();
            this.currentId = keyValue;
        },
        del(row){
           
            this.currentRow  = row;

             if(this.deleteMethod){
                if(!this.deleteMethod.call(this , row ,this.searchForm)){
                    return;
                }
            }
            let keyValue = this.getKeyValue();
            if(!keyValue || keyValue.length==0){
                console.error("主键值不能为空!");
                return;
            }
            this.$confirm('确定删除？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
                let url = "unit/ins/delete?unitName="+this.unitName+"&id=" + keyValue[0];
				_g.openGlobalLoading()
				this.apiGet(url).then((res) => {
					_g.closeGlobalLoading()
					if(res.code==200){
						_g.toastMsg('success', '删除成功')
						setTimeout(() => {
							this.notifyDataChange();
						}, 500)
					}else{
                        _g.toastMsg('error', res.msg);
					}
					
				})
			}).catch(() => {
				// catch error
			})
        },
        sortChange(data){
            let {prop,order} = data;
            this.searchForm.sortProperty = prop;
            this.searchForm.sortDescOrAsc = order == 'descending' ? 'desc' : 'asc';
            this.getDataOfPager();
        },
        handleCurrentChange(val){
            this.currentRow = val
            this.$emit('current-change',val);
        },
        handleSelectionChange(val){
            this.$emit('selection-change',val);
        },
        handleCurrentPageChange(val){
            this.page = val;
            this.getDataOfPager();
        },
        getDataOfPager(){

            if(this.tabs && this.tabs.length>0){
                if(this.tabName!='list'){
                    return;
                }
            }
            let _data = this.searchForm;
            if(this.condition){
                _data = Object.assign(this.searchForm ,this.condition);
            }
            console.log('search form ',_data);
      
            let url = 'unit/ins/getDataOfPager?unitName=' + this.unitName + "&page="+ this.page + "&pageSize=" + this.pageSize;
            _g.openGlobalLoading();
            this.apiPost(url , _data).then(resp=>{
                _g.closeGlobalLoading();
                if(resp && resp.code === 200 && resp.data && resp.data.list){
                    this.tableData = resp.data.list;
                    this.page = resp.data.pageNum;
                    this.pageSize = resp.data.pageSize;
                    this.total = resp.data.total;
                    this.$emit("data-loaded" , resp.data);
                }else{
                    _g.toastMsg('error', res.msg);
                }
            });
        },
        initData(){
            unitProvider.loadUnitDefine(this.unitName).then(data=>{
                if(data){
                    this.buttons = data.buttons ? data.buttons.split(',') : [];
                 
                    if(data.tables){
                        this.checkboxSelect  = data.chkSelect && data.chkSelect == true ? true : false;
                        this.lineNumber = data.lineNumber && data.lineNumber == true? true : false; 
                        this.mTreeCodeType = data.treeCodeType;
                        this.mTreeFieldKey = data.treeFieldKey;
                        this.mTreeFilterFieldKey = data.treeFilterFieldKey;
                        this.mTreeFilterType = data.treeFilterType;
                        // console.log('data',this.$data);
                        data.tables.forEach(t => {
                            if(t.tableType=='master'){
                                if(t.keys){
                                     this.keys = t.keys;
                                }
                                // console.log('table->',t);
                                
                                this.summaryFields = t.summaryFields;
                                this.summaryFields = this.summaryFields.filter(f=>{return f.visible != 2}); //过滤隐藏的列表
                                this.summaryFields.forEach(ft => {
                                    if(ft.formatter){
                                        this.formatters[ft.columnName] = ft.formatter;
                                    }
                                    if(ft.filterable){
                                        this.filterFields.push(ft);
                                    }
                                });
                            }

                            this.initDefaultQueryValue();
                        });

                        //加载数据
                        this.getDataOfPager();
                    }

                }
            });
        },
        updateUI(){

        },
        initDefaultQueryValue(){
            if(this.defaultQueryValue){
                for(let p in this.defaultQueryValue){
                    this.$set(this.searchForm,p,this.defaultQueryValue[p]);
                }
            }
        }
    },
    updated(){
        this.updateUI();
    },
    created(){
        this.initData();
        if(this.initMethod){
            this.initMethod(this.$data);
        }
    },
    mounted(){
        this.routeName = this.$route.name;
        _g.closeGlobalLoading();
    },
    mixins:[http,toolkit]
}
</script>
<style scoped>

</style>


